package com.efast.cafe.commponent.es.tcp.handler;

import com.efast.cafe.commponent.es.tcp.bean.TcpData;
import com.efast.cafe.commponent.es.tcp.utils.CommandConstant;
import com.efast.cafe.commponent.log.ext.CafeLogger;
import com.efast.cafe.commponent.log.ext.CafeLoggerFactory;
import com.efast.cafe.util.ProxyDelegate;
import com.efast.cafe.util.StringUtil;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

public class TcpProcHandler extends ChannelInboundHandlerAdapter{

	
	CafeLogger logger = CafeLoggerFactory.getLogger(getClass());
	
	/**
	 * 该方法调用业务处理类
	 */
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		if(msg instanceof TcpData) {
			TcpData d = (TcpData)msg;
			String className = CommandConstant.getHandler(d.getCommand()+d.getVersion());
			if(StringUtil.isNullOrBlank(className)){
				logger.warn("命令："+d.getCommand()+",协议版本："+d.getVersion()+",没有找到对应的业务实现类。");
			}else{
				Object res = ProxyDelegate.invoke(className,"handMessage",new Object[]{d});
				if(res!=null){
					byte[] resbyte = (byte[])res;
					ctx.channel().writeAndFlush(resbyte).sync();
				}
			}
		}
	}
	
	
	/**
	 *  串通后执行的第一个方法
	*/
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		 logger.info("CHannelHandlerContext ID为"+ctx.channel().id().asLongText()+"连接成功");
		 //to do 
	}
	
	/**
	 * 客户端断开连接  
	 */
	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		 logger.info("CHannelHandlerContext ID为"+ctx.channel().id().asLongText()+"断开连接");
		//to do 
	}
	
	   
	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		ctx.flush();
	}
	
	
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		logger.error("异常发生,关闭客户端！", cause.getMessage());
        cause.printStackTrace();
        ctx.close();
	}
	   
	/**
	 * 心跳超时    
	 */
	@Override
	public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
		 if (evt instanceof IdleStateEvent) {
			 IdleStateEvent e = (IdleStateEvent) evt;
	            if (e.state() == IdleState.READER_IDLE) {
	                ctx.close();
	            }
		 }
	}
}
